<template>
  <p-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <p-spin :spinning="confirmLoading">
      <p-form :form="form">
		  <div class="base-info">基本信息</div>
        <p-row>
		  <p-col  :span="8">
			<p-form-item label="任务编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input readOnly :disabled="isQuery" v-decorator="[ 'scientificOrder', validatorRules.scientificOrder]" placeholder="请输入任务编号"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-select-user-by-dep :disabled="isQuery" v-decorator="['scientificPlease', validatorRules.scientificPlease]" :trigger-change="true"/>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="部门名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-select-depart :disabled="isQuery" v-decorator="['dptno', validatorRules.dptno]" :trigger-change="true"/>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery"  v-decorator="[ 'scientificContact', validatorRules.scientificContact]" placeholder="请输入联系方式"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery"  v-decorator="[ 'scientificname', validatorRules.scientificname]" placeholder="请输入项目名称"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="项目编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'scientificno', validatorRules.scientificno]" placeholder="请输入项目编码"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="加工类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-dict-select-tag :disabled="isQuery" type="list" v-decorator="['scientificType', validatorRules.scientificType]" :trigger-change="true" dictCode="mes_scientific_type" placeholder="请选择加工类型"/>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="项目经理" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'scientificManager', validatorRules.scientificManager]" placeholder="请输入项目名称"></p-input>
			</p-form-item>
		  </p-col>	  
		  <p-col  :span="8">
			<p-form-item label="加工说明" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'scientificInstructions', validatorRules.scientificInstructions]" placeholder="请输入项目名称"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="BOMreport" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-upload @change="changeOkUpload" :disabled="isQuery" v-decorator="['bomReport', validatorRules.bomReport]" :trigger-change="true"></j-upload>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="科研bom表" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-upload @change="changeOkUpload1" :disabled="isQuery" v-decorator="['researchBom', validatorRules.researchBom]"  :trigger-change="true"></j-upload>
			</p-form-item>
		  </p-col>
          
        </p-row>

        <div class="base-info">加工内容</div>
		<p-row>
		  <p-col  :span="8">
			<p-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'name', validatorRules.name]" placeholder="请输入名称"></p-input>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="型号/图号（版号）" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'model', validatorRules.model]" placeholder="请输入型号/图号（版号）"></p-input>
			</p-form-item>
		  </p-col>

		  <p-col  :span="8">
			<p-form-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery"  v-decorator="[ 'quantity', validatorRules.quantity]" placeholder="请输入数量"></p-input>
			</p-form-item>
		  </p-col>

		  <p-col  :span="8">
			<p-form-item label="需求完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-date  :disabled="isQuery"  placeholder="请输入需求完成时间" v-decorator="[ 'contentTime', validatorRules.contentTime]" :trigger-change="true" style="width: 100%"/>
			</p-form-item>
		  </p-col>

		  <p-col  :span="8">
			<p-form-item label="成本中心" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-input :disabled="isQuery" v-decorator="[ 'costCenter', validatorRules.costCenter]" placeholder="请输入成本中心"></p-input>
			</p-form-item>
		  </p-col>

		  <p-col  :span="8">
			<p-form-item label="物料齐套时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-date  :disabled="isQuery"  placeholder="请输入物料齐套时间" v-decorator="[ 'scientificQitime', validatorRules.scientificQitime]" :trigger-change="true" style="width: 100%"/>
			</p-form-item>
		  </p-col>

		  <p-col  :span="8">
			<p-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-upload @change="changeOkUpload2" :disabled="isQuery" v-decorator="['accessory', validatorRules.accessory]" :trigger-change="true"></j-upload>
			</p-form-item>
		  </p-col>
		  </p-row>
		   <div v-if="isQuery && model.status===3" > <!--v-if="model.status ===3" -->
		  <div class="base-info">外协厂家范围</div>
              <div class="base-info-supplier">
				  {{supplierStr || '暂无数据'}}
			  </div>
		   </div>
		   <!-- v-if="model.status ===2" -->
		  <div v-if="isQuery && model.status ===2" class="base-info" >工艺路线维护 <p style="float:right;" @click="closeModal">查询</p></div>
		  
		  <div  v-if="isQuery && model.status===4"> <!--v-if="model.status===4" -->
		  <div class="base-info">采购评审</div>
		  <p-row>
			<p-col :span="8">
			 <!-- <p-form-item label="选择供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
				 <p-input type="textarea" v-decorator="[ 'costCenter', validatorRules.costCenter]" placeholder="请输入选择供应商"></p-input>
			 </p-form-item> -->
			 <div class="base-info-supplier">
                <p-checkbox-group
				v-if="plainOptions.length"
				v-model="checkboxGroupList"
				:options="plainOptions"
				@change="onHandleChangeCheckbox"
				>
				</p-checkbox-group>
				<span v-else>暂无数据</span>
			 </div>
			</p-col>
		   </p-row>
		  </div>

		<div v-if="isQuery && model.status===5">
		  <div class="base-info">事业部确认</div>
		  <p-row>
		  <p-col  :span="8">
			<p-form-item label="实际领用时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-date    placeholder="请输入实际领用时间" v-decorator="[ 'actualStartTime', validatorRules.actualStartTime]" :trigger-change="true" style="width: 100%"/>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="计划完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-date    placeholder="请输入计划完成时间" v-decorator="[ 'scientificCompleteTime', validatorRules.scientificCompleteTime]" :trigger-change="true" style="width: 100%"/>
			</p-form-item>
		  </p-col>
		  <p-col  :span="8">
			<p-form-item label="实际完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<j-date    placeholder="请输入实际完成时间" v-decorator="[ 'actualFinishTime', validatorRules.actualFinishTime]" :trigger-change="true" style="width: 100%"/>
			</p-form-item>
		  </p-col>	
		  <p-col  :span="8">
			<p-form-item label="实际完成情况" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<p-select placeholder="请输入实际完成情况" @change="changeCompletion" v-decorator="['actualCompletion', validatorRules.actualCompletion]" >
				<p-select-option v-for="item in tagList" :key="item" :value="item.value">
					{{ item.label }}
				</p-select-option>
				</p-select>
			</p-form-item>
		  </p-col>
		  </p-row>
		  </div>
      </p-form>
    </p-spin>
	<section slot="footer">
		<p-button v-if="isQuery" @click="handleManageBack()">回退</p-button>
		<p-button @click="close">取消</p-button>
		<p-button v-if="!model.id && model.status===4" @click="handleSave" >保存</p-button>
		<p-button type="primary" v-if="!isQuery" @click="handleOk">提交</p-button>  <!--表单提交 -->
		<p-button type="primary" v-if="isQuery" @click="businessConfirm">提交</p-button><!--状态操作提交 -->
	</section>
  </p-modal>
</template>

<script>


  import { SubmitOnchangMixin } from '@/mixins/SubmitOnchangMixin'
  import { httpAction, putAction,getAction, api } from '@/api/manage'
  import moment from 'moment'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"

  export default {
    name: "MesMfScientificModal",
	mixins: [SubmitOnchangMixin],
    components: { 
      JDate,
      JUpload,
      JSelectDepart,
      JSelectUserByDep,
	  JDictSelectTag,
    },
    data () {
      return {
        form: this.$form.createForm(this),
        width: 1200,
		visible: false,
		isQuery:false,
		supplierStr:'',
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
        scientificOrder:{rules: [{ required: true, message: '请输入任务编号!' }]},
        scientificPlease:{rules: [{ required: true, message: '请输入申请人!' }]},
        dptno:{rules: [{ required: true, message: '请输入部门名称!' }]},
        scientificContact:{rules: [{ required: true, message: '请输入联系方式!' }]},
        scientificno:{rules: [{ required: true, message: '请输入项目编码!' }]},
        scientificname:{rules: [{ required: true, message: '请输入项目名称!' }]},
        scientificClassification:{},
        scientificType:{rules: [{ required: true, message: '请输入加工类型!' }]},
		name:{rules: [{ required: true, message: '请输入名称!' }]},
        contentTime:{rules: [{ required: true, message: '请输入需求完成时间!' }]},
        model:{rules: [{ required: true, message: '请输入型号/图号（版号）!' }]},
        scientificStarttime:{rules: [{ required: true, message: '请输入计划开始时间!' }]},
        scientificQitime:{rules: [{ required: true, message: '请输入实际物料齐套时间!' }]},
        scientificState:{rules: [{ required: true, message: '请输入当前状态!' }]},
        bomReport:{},
		researchBom:{},
		costCenter:{rules: [{ required: true, message: '请输入成本中心!' }]},
		quantity:{rules: [{ required: true, message: '请输入数量!' }]},
		scientificInstructions:{rules: [{ required: true, message: '请输入加工说明!' }]},
		scientificManager:{rules: [{ required: true, message: '请输入项目经理!' }]},
        accessory:{},
        supno:{rules: [{ required: true, message: '请输入供应商编码!' }]},
        supname:{rules: [{ required: true, message: '请输入供应商名称!' }]},
        scientificCompleteTime:{},
        actualStartTime:{},
        actualFinishTime:{},
        actualCompletion:{},
		},
		manageBack:'',//回退
		files:{file1:'',file2:'',file3:''},
        url: {
          add: '/mes-manufacture/mfScientific',  //保存
		  edit: '/mes-manufacture/mfScientific/submit', //提交
		  businessConfirm:'/mes-manufacture/mfScientific/business/confirm',
		  supplier:'/mes-manufacture/mfSuggest/',
		  procurement:'/mes-manufacture/mfSuggest/purchase/approve', //采购提交
		  savePurchase:'/mes-manufacture/mfSuggest/purchase'//采购保存
		},
		tagList:[
		{label:'正常',value:0},
		{label:'滞后',value:1},
		{label:'提前',value:2},
		],
		plainOptions:[],
		checkboxGroupList:[],
      }
    },
    created () {
	},
	mounted(){
		console.log(this.title)
	},
    methods: {
		changeCompletion(data){
			this.model.actualCompletion = data
			console.log(this.model);
			},
      add () {
        this.edit({});
        this.getRuleCodeValue();
      },
      getRuleCodeValue() {
        let param = {
          commonFormData: this.model,
          rules: [
            {"ruleCode": "rwbh", "columnName": "scientificOrder"},
            ]
        }

        putAction(api.ruleBaseURL, param).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
			console.log("生成的编码：" + res.data)
            const item = res.data.scientificOrder? res.data : {scientificOrder:(new Date()).valueOf()};
            this.form.setFieldsValue(pick(item, Object.keys(item)))
          }
        })
      },
      edit (record,isQuery) {
		this.form.resetFields();
		console.log(this.title)
		if(isQuery===1){
			this.isQuery = true
		}else{
			this.isQuery = false
		}
		this.model = Object.assign({}, record);
		this.getSupplierList(this.model.id)
        this.visible = true;
        this.$nextTick(() => {
		   const {scientificStarttime,scientificQitime,contentTime,actualStartTime,actualFinishTime,scientificCompleteTime} = this.model
		   this.model.scientificQitime = moment(scientificQitime)
		   this.model.scientificStarttime = moment(scientificStarttime)
		   this.model.contentTime = moment(contentTime)
		  this.form.setFieldsValue(pick(this.model,'scientificOrder','scientificPlease',
		  'dptname','scientificContact','scientificno','scientificname',
		  'scientificClassification','scientificType','name','contentTime','model',
		  'scientificStarttime','scientificQitime','scientificState','bomReport',
		  'researchBom','accessory','supno','supname','scientificCompleteTime',
		  'actualStartTime','actualFinishTime','actualCompletion','costCenter',
		  'scientificManager','dptno','quantity','scientificInstructions',
		  'createTime','updateBy','updateTime'))
		})
		
		
      },
      close () {
        this.$emit('close');
        this.visible = false;
	  },
	  closeModal(){
		this.$emit('closeModal',this.model.id);
		this.visible = false;
	  },
	  initFileListArr(val){
        let fileList = [];
        for(var a=0;a<val.length;a++){
          fileList.push({
            uid:uidGenerator(),
            name:val[a].fileName,
            status: 'done',
            url: val[a].filePath,
            response:{
              status:"history",
              message:val[a].filePath
            }
          })
        }
        return fileList  
      },
	  changeOkUpload(data){
		//   this.model.bomReport = data[0].response.data
		// this.model.bomReport=this.initFileListArr(data)
		  console.log(data)
		  if(data){
           this.files.file1=data
		  }
		  console.log(this.model)
	  },
	  changeOkUpload1(data){
		  console.log(data)
		  if(data){
           this.files.file2=data
		  }
		//   this.model.researchBom = data[0].response.data
	  },
	  changeOkUpload2(data){
		  console.log(data)
		  if(data){
           this.files.file3=data
		  }
		//   this.model.accessory = data[0].response.data
	  },
	  onHandleChangeCheckbox(val){
	   console.log(val)
	   console.log(this.checkboxGroupList)
	  },
	  modalFrom(url,params,method){
         httpAction(url,params,method).then(res=>{
			 console.log(res)
			 this.close()
			 this.modalFormOk()
		 })
	  },
	  //供应商建议
	  getSupplierList(id,params){
		  getAction(this.url.supplier+id,params).then(res=>{
			  console.log(res)
			  if(res.code === 0 && res.data){
			   this.supplierStr = res.data.map(item=>item.supname).toString()
			   this.plainOptions = res.data
			   this.plainOptions.map(item=>{
				   item.label = item.supname;
				   item.value = item.supno
			   })
			  }
	    })
	  },
      //保存
	  handleSave(){
         if(this.modal.status===4){
			const info={
				mesMfScientificId:this.model.id,
                suggestEditParamList:[]
			}
			this.checkboxGroupList.map(item=>{
				info.suggestEditParamList.push({supno:item})
			})
           httpAction(this.url.savePurchase,info,'put').then(res=>{
			   if(res.code === 0){this.$message.success('操作成功')}
                
		   })
		 }
	  },
	  //回退
	  handleManageBack(str){
          if(this.model.status===2){
             this.manageBack = '/mes-manufacture/mfProcessRouteMaintenance/back/' //工艺维护
		  }else if(this.model.status===3){
             this.manageBack = '/mes-manufacture/mfSuggest/back/' //建议
		  }else if(this.model.status===4){
             this.manageBack = '/mes-manufacture/mfSuggest/purchase/back/' //采购
		  }else if(this.model.status===5){
             this.manageBack = '/mes-manufacture/mfScientific/back/' //生管
		  }
		getAction(this.manageBack+this.model.id,'get').then(res=>{
			this.close()
			this.modalFormOk()
		})
	  },
		handleOk () {
			console.log(this.$form.createForm(this))
			const that = this;
			// 触发表单验证
			this.form.validateFields((err, values) => {
			  if (!err) {
				  that.confirmLoading = true;
				  let httpurl = '';
				  let method = '';
				  console.log(values)
				  let formData = Object.assign(this.model, values);
				  this.formData = Object.assign(this.model, values);
				  if(this.files.file1){
					  formData.bomReport = this.files.file1
				  }
				  if(this.files.file2){
					  formData.researchBom = this.files.file2
				  }
				  if(this.files.file3){
					  formData.accessory = this.files.file3
				  }
				  //新增触发
				  if(!this.model.id){
					httpurl+=this.url.add;
					method = 'post';
					if(this.EnhanceJS.afterAdd){
					  //新增之前
					  let Obj = eval(this.EnhanceJS.afterAdd)
					  new Obj(this)
					}else{
					  console.log("表单提交数据",formData)
					  console.log(formData)
					  that.modalFrom(httpurl,formData,method)
					}
				  }else{
					//编辑触发
					httpurl+=this.url.edit;
					method = 'post';
					if(this.EnhanceJS.afterEdit){
					 //编辑之前
					  let Obj = eval(this.EnhanceJS.afterEdit)
					  new Obj(this)
					}else{
					  console.log("表单提交数据",formData)
					  console.log(formData)
					  that.modalFrom(httpurl,formData,method)
					}
				  }
			  }

			})
		},
        //事业部确认
		businessConfirm(){
            const that = this;
			this.form.validateFields((err, values) => {
			  if (!err) {
				  that.confirmLoading = true;
				  let httpurl = '';
				  let method = '';
				  console.log(values)
				  let formData = Object.assign(this.model, values);
				  this.formData = Object.assign(this.model, values);
				  if(this.model.status===2){ //工艺路线维护
                    httpurl = this.url.edit;
					method = 'put';
					that.modalFrom(httpurl,formData,method)
				  }else if(this.model.status===3){ //外协厂家范围
                    httpurl = this.url.edit;
					method = 'put';
					that.modalFrom(httpurl,formData,method)
				  }else if(this.model.status===4){ //采购确认
                    httpurl = this.url.procurement;
					method = 'put';
					that.modalFrom(httpurl,formData,method)
				  }else if(this.model.status===5){ //事业部确认
                    httpurl = this.url.businessConfirm;
					method = 'put';
					that.modalFrom(httpurl,formData,method)
				  }
				  
			  }

			})

		},

      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'scientificOrder','scientificPlease','dptname','scientificContact','scientificno','scientificname','scientificClassification','scientificType','name','contentTime','model','scientificStarttime','scientificQitime','scientificState','bomReport','researchBom','accessory','supno','supname','scientificCompleteTime','actualStartTime','actualFinishTime','actualCompletion','createBy','createTime','updateBy','updateTime'))
      },

      
    }
  }
</script>

<style lang="less" scoped>
.base-info{
	width: 100%;
	background-color: gainsboro;
	padding:5px 10px;
	margin-bottom: 10px;
	
}
.base-info-supplier{
		border: 1px solid rgb(170, 166, 166);
		width: 280px;
		height: 80px;
		padding:0 5px;
		margin: 10px 0;
	}
</style>
